<template>
    <el-dialog class="ui-add-goods-dialog ui-dark-dialog" v-model="dialogVisible" :title="title" ref="dialog" @closed="finalThings">
        <el-form ref="elForm" :model="data" :rules="rules" @submit.prevent="onSure" label-width="6rem">
            <div class="box-row">
                <div class="ui-fields">
                    <el-form-item label="商品类型:" prop="prop">
                        <el-radio-group v-model="data.prop" :disabled="!iscreate" @change="onGoodsPropChanged">
                            <el-radio :label="0">计算库存</el-radio>
                            <el-radio :label="1">不计库存</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品名称:" prop="name">
                        <el-input v-model="data.name"></el-input>
                    </el-form-item>
                    <div class="box-row">
                        <div style="flex:1">
                            <el-form-item label="商品条码:" prop="code" :required="!data.inside">
                                <el-autocomplete style="width:100%;" popper-class="ui-goods-suggest" highlight-first-item fit-input-width value-key="code" v-model="data.code" :disabled="data.inside || !iscreate" :fetch-suggestions="onSearchGoods" @select="onCodeSelected">
                                    <template #default="{ item }">
                                        <div class="it-code">{{ item.code }}</div>
                                        <span class="it-name">{{ item.name }}</span>
                                    </template>
                                </el-autocomplete>
                            </el-form-item>
                        </div>
                        <div v-if="iscreate">
                            <el-form-item label-width="3.8rem" label="店内码:" prop="inside" @change="onInsideChanged">
                                <el-checkbox v-model="data.inside" :disabled="!iscreate"></el-checkbox>
                            </el-form-item>
                        </div>
                    </div>
                    <el-form-item label="商品售价:" prop="sale_price">
                        <el-input-number class="op-num-ipt" v-model="data.sale_price" :min="0" :controls="false" :precision="2" :step="0.01"></el-input-number>
                    </el-form-item>
                    <el-form-item label="整箱数量:" prop="pack_size" v-if="data.prop==0 || data.prop==2">
                        <el-input-number class="op-num-ipt" v-model.number="data.pack_size" :min="0" :controls="false" :precision="0" :step="1" ></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品描述:" prop="spec">
                        <el-input v-model="data.spec"></el-input>
                    </el-form-item>              
                </div>
                <div class="ui-uploader">
                    <el-upload 
                        class="img-uploader"
                        action="https://file.80mall.net"
                        :show-file-list="false"
                        accept="image/png, image/jpeg, image/jpg"
                        name="image"
                        :http-request="uploadFile"
                    >
                        <img v-if="data.img" :src="'https://avatar.80mall.net/photo' + data.img" class="avatar" />
                        <i v-else class="ui-ico-add"></i>
                    </el-upload>
                </div>
            </div>
            <el-form-item label="商品分类:" prop="category_ids">
                <el-checkbox-group v-model="data.category_ids">
                    <el-checkbox 
                        v-for="(cat,index) in categorys" 
                        v-bind:key="cat.id" 
                        :label="cat.id"
                        :disabled="index == 0 || data.prop == 2"
                    >
                        {{cat.name}}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-checkbox v-if="iscreate" v-model="checked" label="继续添加" size="large" style="margin-right: 10px;"/>
            <el-button size="default" type="primary" @click="onSure">确定</el-button>
            <el-button size="default" type="danger" @click="onCancel">取消(Esc)</el-button>
        </template>
    </el-dialog>
</template>
<script>
import { reactive, toRefs } from 'vue'
import { ElMessage,ElUpload } from 'element-plus';
import { checkEan13, checkRmb,checkInt } from '../../uiframe/validator';
import { uploader } from '../../uiframe/extiio';
import axios from 'axios';
import { isEan13Code } from '../../uiframe/validator';

export default {
    components:{
        ElUpload,
    },
    props: {
        q: Object,
        _compId: Number,
        done: Function,
        payload: Object,
        categorys: Array
    },
    setup(props) {
        let timeout = null, matched=[], ini = Object.assign({prop:0, inside:false, desc:''},props.payload),
            iscreate = props.payload ? false : true,
            isupdate = false;
        console.log(iscreate);
        let data = reactive({
            title: iscreate ? '添加商品':'修改商品',
            iscreate,
            dialogVisible: true,
            checked:false,
            data: JSON.parse(JSON.stringify(ini)),
            elForm:null,
            categorys:props.categorys,
            rules:{
                prop:[{required:true, message:'商品类型不能为空.'}],
                name: [{required:true, message:'商品名称不能为空.'}],
                code: [
                    {required:true, message:'商品条码不能为空.'},
                    {validator: (r,v,c)=>iscreate  && ! data.inside ? checkEan13(r,v,c) : c(), message:'条码不合法?.'}
                ],
                sale_price: [
                    {required:true, message:'商品售价不能为空.'},
                    {validator:checkRmb, message:'价格不合法.'},
                ],
                img: [{required:true, message:'商品照片不能为空.'}],
                pack_size:[
                    {required:true, message:'整箱数量不能为空.'},
                    {validator:checkInt, message:'必须是整数.'},
                ],
                category_ids:[
                    {required:true, message:'商品分类必选.'},
                ]
            }
        });

        if(iscreate){
            ini.category_ids = data.data.category_ids = [data.categorys[0].id];
        }

        const events = {
            onCancel : ()=>data.dialogVisible = false,
            finalThings: () =>{
                if(isupdate) props.q.resolve({success:true,message:'', data:[]});
                props.done(props._compId);
            },
            onGoodsPropChanged:()=>{
                if(data.data.prop==2){
                    data.data.category_ids = [data.categorys[0].id];
                    data.data.on_sale = false;
                }
            },
            onInsideChanged:()=>{
                if(data.inside){
                    data.data.code = '';
                    data.elForm.clearValidate('code');
                }else{
                    data.elForm.validateField('code');
                }
            },
            onSearchGoods:(input, callback) => {
                clearTimeout(timeout);
                if(matched.length > 0 && isEan13Code(data.data.code)){
                    callback(matched);
                    return;
                }
                axios.post('/goods/match',{code:input}).then(({data:res})=>{
                    matched = res.data;
                    callback(matched);
                })
            },
            onCodeSelected:()=>{
                let g = matched.find(item=>item.code == data.data.code)
                if(g){
                    ['name','img','sale_price','img','pack_size','sale_price'].forEach(key=>{
                        data.data[key] = g[key];
                    })
                    matched = [g];
                }
            }
        },
        onmessage = (msg) =>ElMessage({ type: msg.success?'success':'error', message: msg.message }),
        methods = {
            onSure: () => {
                data.elForm.validate().then(res=>{
                    if(!res) return;

                    if(data.data.prop !=2 && !data.data.img){
                        onfailure({message:'商品图片不能为空.'})
                        return false
                    }

                    axios.post('/goods/save',data.data).then(({data:res})=>{
                        onmessage(res)
                        isupdate = true;
                        if(data.checked){
                            data.data = ini;
                        }else{
                            if(res.success){
                                data.dialogVisible = false;
                            }
                        }
                    })
                })
            },
            uploadFile:(upload) => {
                return new Promise((resolve, reject)=>{
                    uploader(upload.action, upload.file, 'goods').then(({data:res})=>{
                        !res.success && onmessage(res)
                        if(res.success){
                            data.data.img = res.file;
                        }
                        resolve();
                    }).catch(e=>{
                        onfailure({message:"程序出错，请联系工作人员！"});
                        reject()
                    }).update(e=>{
                        upload.onProgress(e);
                    })
                })
            }
        }
        
        return {
            ...toRefs(data),
            ...events,
            ...methods
        }
    }
}
</script>
<style lang="scss">
.ui-add-goods-dialog {
    width: 40rem;
    max-width: 40rem;
    .ui-fields{
        flex:1;
    }
    .ui-uploader{
        padding: 3rem 0 0 2rem;
        .el-upload{
            width: 10rem; height: 10rem;
        }
    }
    .op-num-ipt{
        width: 100%;
        input{text-align: left;}
    }

    

    .img-uploader .el-upload{
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 10rem; height: 10rem;
        line-height: 162px;
    }
    .img-uploader .el-upload:hover {
        border-color: #409eff;
    }
    .img-uploader .avatar{
        display: block;
        width: 10rem; height: 10rem;
    }
    i[class*=ui-ico-]{
        font-size: 2rem;
    }
}
.ui-goods-suggest{
    li{
        line-height: 1rem;
        .it-code{font-size:.75rem;color:var(--el-primary-color);margin-top: .25rem;}
        .it-name{font-size:.75rem;color:#A89;margin-bottom: .25rem;}
    }
}
</style>